import { MapIcons } from '@/utils/base64-icons'
import { toRaw, nextTick } from 'vue';
import { debounce } from 'lodash'
import { centerOfMass } from '@turf/turf'

const gl = {
    VECTORLAYER: 'https://ai.ht1y.com'
}
export default {
    data() {
        return {
            map: null,
            source_data: {},
            currentMode: '',
            currentKey: '',
            searchForKey: '',
            displayAll: true,
            isLotgla: false,
            isGeodetic: false,
            isShowLGLayers: false,
            containKeys: [],
            center: [114.17218, 22.29770],
            layerOrder: ['searchFor-customLayer-layer', 'enterprise-point-layer', 'geodetic-BM_point-layer', 'geodetic-Traverse_point-layer', 'geodetic-Trig_point-layer', 'lotgla-polygon-layer'],
            zoom: 10,
            minZoom: 0,
            maxZoom: 20,
            tileSize: 256,
            hkBounds: [
                [113.5, 21.8],
                [114.7, 22.85]
            ],
            // hkBounds: [
            //     [73.5, 18.0],
            //     [135.0, 53.5]
            // ],
            currentLocation: {
                status: false,
                center: [],
                title: '',
                params: {},
                node: '',
            }
        }
    },
    mounted() {
        this.loadOpenLayers(() => {
            this.initMap()
        })
    },
    watch: {
        isLotgla: {
            handler: debounce(function (newVal, oldVal) {
                if (!!this.isShowLGLayers && (this.currentMode === 'searchFor' || this.currentMode === 'hk1980' || this.currentMode === 'geodetic' || this.currentMode === 'lotgla')) {
                    if (newVal == true) {
                        this.loadVectorTileLayer()
                    }
                    this.lotgla_pointchecked_state()
                    this.locationAllocationFontLayer_state()
                }
            }, 300),
            immediate: false
        },
        isGeodetic: {
            handler: debounce(function (newVal, oldVal) {
                if (!!this.isShowLGLayers && (this.currentMode === 'searchFor' || this.currentMode === 'hk1980' || this.currentMode === 'geodetic' || this.currentMode === 'lotgla')) {
                    if (newVal == true) {
                        this.fetchGeodeticPointsInView()
                        this.checkTheLandingPointOfTheEnterprise()
                    }
                    this.geodetic_pointchecked_state()
                    this.enterprise_pointchecked_state()
                }
            }, 300),
            immediate: false
        }
    },
    methods: {
        /**
         * 获取平台路径
         * @param {string} relativePath 相对路径
         * @returns {string} 平台路径
         * @example
         * getPlatformPath('static/icon/marker.png')
         */
        getPlatformPath(relativePath) {
            // #ifdef APP-PLUS
            return plus.io.convertLocalFileSystemURL(`_www/${relativePath}`);
            // #endif
            // #ifdef H5
            return `/${relativePath}`;
            // #endif
        },
        loadOpenLayers(callback) {
            if (window.maplibregl) return callback();

            const css = document.createElement('link');
            css.rel = 'stylesheet';
            css.href = this.getPlatformPath('static/openlayers/maplibre-gl.css');
            document.head.appendChild(css);

            const mapboxScript = document.createElement('script');
            mapboxScript.src = this.getPlatformPath('static/openlayers/maplibre-gl.js');
            mapboxScript.onload = callback;
            document.head.appendChild(mapboxScript);
        },
        initMap() {

            this.map = new maplibregl.Map({
                container: 'map',
                center: this.center,
                zoom: this.zoom,
                minZoom: this.minZoom,
                maxZoom: this.maxZoom,
                style: {
                    version: 8,
                    sources: {},
                    layers: [],
                    glyphs: gl.VECTORLAYER + '/fonts/{fontstack}/{range}.pbf'
                },
                maxBounds: this.hkBounds
            });


            this.map.on('load', () => {

                this.$ownerInstance.callMethod('loadDynamicIcons');

                //初始化注册图标
                const baseImg = new Image();
                baseImg.src = MapIcons.svgico;
                baseImg.onload = async () => {
                    const iconSize = 256;
                    const cropIcon = (xIndex, yIndex) => {
                        const canvas = document.createElement('canvas');
                        canvas.width = iconSize;
                        canvas.height = iconSize;
                        const ctx = canvas.getContext('2d');
                        if (!ctx) {
                            return null;
                        }
                        ctx.drawImage(baseImg,
                            xIndex * iconSize, yIndex * iconSize, iconSize, iconSize,
                            0, 0, iconSize, iconSize
                        );
                        return canvas;
                    }
                    for (let i = 0; i < 6; i++) {
                        const xIndex = i % 2;  // 横坐标
                        const yIndex = Math.floor(i / 2);  // 纵坐标
                        if (!this.map.hasImage(`icon-${yIndex}-${xIndex}`)) {
                            const canvas = cropIcon(xIndex, yIndex);
                            if (!canvas) {
                                continue;
                            }
                            const bitmap = await createImageBitmap(canvas);
                            this.map.addImage(`icon-${yIndex}-${xIndex}`, bitmap);
                        }
                    }
                };

                this.map.loadImage(MapIcons.point[2], (error, image) => {
                    if (error) {
                        console.error('加载图片失败:', error);
                        return;
                    }
                    if (!this.map.hasImage('my-points-icon')) {
                        this.map.addImage('my-points-icon', image);
                    }
                });

                for (let index in MapIcons.point) {
                    this.map.loadImage(MapIcons.point[index], (error, image) => {
                        if (error) {
                            console.error('加载图片失败:', error);
                            return;
                        }
                        if (!this.map.hasImage(`my-points-icon-${index}`)) {
                            this.map.addImage(`my-points-icon-${index}`, image);
                        }
                    });
                }

                this.map.addSource('hk-basemap', {
                    type: 'raster',
                    tiles: [
                        'https://mapapi.geodata.gov.hk/gs/api/v1.0.0/xyz/basemap/wgs84/{z}/{x}/{y}.png'
                    ],
                    tileSize: this.tileSize,
                    attribution: '© 香港特別行政區政府地理資訊系統'
                })

                this.map.addSource('hk-labels', {
                    type: 'raster',
                    tiles: [
                        'https://mapapi.geodata.gov.hk/gs/api/v1.0.0/xyz/label/hk/tc/wgs84/{z}/{x}/{y}.png'
                    ],
                    tileSize: this.tileSize
                })

                this.map.addLayer({
                    id: 'hk-basemap-layer',
                    type: 'raster',
                    source: 'hk-basemap'
                })

                this.map.addLayer({
                    id: 'hk-labels-layer',
                    type: 'raster',
                    source: 'hk-labels'
                })

                this.map.dragRotate.disable()
                this.map.touchZoomRotate.disableRotation()
                this.map.keyboard.disableRotation()

                this.map.moveLayer('hk-labels-layer')


                this.map.addControl(
                    new maplibregl.ScaleControl({
                        maxWidth: 130,
                        unit: 'metric'
                    }),
                    'bottom-right'
                );

            });
            this.map.on('move', () => {
                if (this.currentMode == "hk1980" || this.currentMode == "searchFor" || this.currentMode == "geodetic" || this.currentMode == "lotgla") {
                    this.moveTooltip()
                }
            })
            this.map.on('moveend', () => {
                this.locationAllocationFontLayer();
            })
            this.map.on('zoomend', () => {
                if (this.currentMode == "hk1980" || this.currentMode == "searchFor" || this.currentMode == "geodetic" || this.currentMode == "lotgla") {
                    this.moveTooltip()
                }
            })
            this.map.on('error', (e) => { })
        },
        checkTheLandingPointOfTheEnterprise() {
            const layerExists = this.map.getLayer('enterprise-point-layer') !== undefined;
            const sourceExists = this.map.getSource('enterprise-geojson-source') !== undefined;
            if (!layerExists && !sourceExists) {
                this.$ownerInstance.callMethod('getAllGeodetic');
            }
        },
        // 企业落点maplibre-gl的mbtiles
        fetchEnterprisePointsInView(enterprisePoints) {
            if (!enterprisePoints || enterprisePoints.length <= 0) return;

            const layerExists = this.map.getLayer('enterprise-point-layer') !== undefined;
            const sourceExists = this.map.getSource('enterprise-geojson-source') !== undefined;
            if (!layerExists && !sourceExists) {

                this.map.addSource('enterprise-geojson-source', {
                    type: 'geojson',
                    data: this.convertToGeoJSON(enterprisePoints)
                });

                this.map.addLayer({
                    id: 'enterprise-point-layer',
                    type: 'symbol',
                    source: 'enterprise-geojson-source',
                    layout: {
                        'icon-image': 'product-{CLASSIFY_ID}-{ORDERSTATUS}-0',
                        'text-allow-overlap': true,
                        'icon-allow-overlap': true,
                        'icon-size': 0.06,
                        'icon-anchor': 'center',
                        'icon-offset': [0, 0]
                    }
                });

                this.map.addLayer({
                    id: 'enterprise-point-highlight-layer',
                    type: 'symbol',
                    source: 'enterprise-geojson-source',
                    layout: {
                        'icon-image': 'product-{CLASSIFY_ID}-0-1',
                        'text-allow-overlap': true,
                        'icon-allow-overlap': true,
                        'icon-size': 0.06,
                        'icon-anchor': 'center',
                        'icon-offset': [0, 0]
                    },
                    filter: ['==', 'STN_NO', this.currentKey]
                });

                this.map.addLayer({
                    id: 'enterprise-point-highlight-text-layer',
                    type: 'symbol',
                    source: 'enterprise-geojson-source',
                    minzoom: 14,
                    layout: {
                        'text-field': '{STN_NO}',
                        'text-font': ['SYCN Normal'],
                        'text-offset': [2, -1],
                        'text-size': [
                            'interpolate',
                            ['linear'],
                            ['zoom'],
                            14, 8,
                            17, 10,
                            20, 16
                        ],
                        'text-allow-overlap': true,
                        'icon-allow-overlap': true
                    },
                    paint: {
                        'text-color': '#ffc107',
                        'text-halo-color': '#ffffff',
                        'text-halo-width': 2
                    }
                });

                this.map.on('click', 'enterprise-point-layer', this.unifiedLayerClickEvent);
                this.map.on('mouseenter', 'enterprise-point-layer', this.handleLotglaPolygonMouseenter);
                this.map.on('mouseleave', 'enterprise-point-layer', this.handleLotglaPolygonMouseleave);
                this.map.on('mouseenter', 'enterprise-point-highlight-layer', this.handleLotglaPolygonMouseenter);
                this.map.on('mouseleave', 'enterprise-point-highlight-layer', this.handleLotglaPolygonMouseleave);

            }
        },

        convertToGeoJSON(data) {
            const features = data.map(item => ({
                type: 'Feature',
                geometry: {
                    type: 'Point',
                    coordinates: [item.X, item.Y]
                },
                properties: item
            }));

            return {
                type: 'FeatureCollection',
                features
            };
        },
        //企业落点maplibre-gl的mbtiles点击事件
        enterprise_point_click(e) {
            const feature = e.features?.[0];
            if (!feature || this.currentKey === feature.properties.STN_NO) return;

            this.currentKey = feature.properties.STN_NO;

            if (this.currentMode != 'hk1980' && this.currentMode != 'geodetic') this.removeTooltip()
            this.currentRenderCallback(this.currentKey, 'geodetic');

        },
        //企业落点maplibre-gl的mbtiles点击事件
        enterprise_pointchecked_state() {
            const isVisibleLocal = !this.isGeodetic
            const filterValue = isVisibleLocal ? 'visible' : this.currentKey

            if (this.map.getLayer('enterprise-point-layer'))
                this.map.setFilter('enterprise-point-layer', [isVisibleLocal ? '==' : '!=', 'STN_NO', filterValue])

            if (this.map.getLayer('enterprise-point-highlight-text-layer'))
                this.map.setFilter('enterprise-point-highlight-text-layer', [isVisibleLocal ? '==' : '!=', 'STN_NO', ''])

            if (this.map.getLayer('enterprise-point-highlight-layer'))
                this.map.setFilter('enterprise-point-highlight-layer', [isVisibleLocal ? '==' : '==', 'STN_NO', filterValue])
        },
        //企业测量落点移除maplibre-gl的mbtiles
        removeEnterpriseVectorTileLayer() {
            if (this.map.getLayer('enterprise-point-layer')) {
                this.map.off('click', 'enterprise-point-layer', this.unifiedLayerClickEvent);
                this.map.off('mouseenter', 'enterprise-point-layer', this.handleLotglaPolygonMouseenter);
                this.map.off('mouseleave', 'enterprise-point-layer', this.handleLotglaPolygonMouseleave);
                this.map.removeLayer('enterprise-point-layer');
            }

            if (this.map.getLayer('enterprise-point-highlight-layer')) {
                this.map.off('mouseenter', 'enterprise-point-highlight-layer', this.handleLotglaPolygonMouseenter);
                this.map.off('mouseleave', 'enterprise-point-highlight-layer', this.handleLotglaPolygonMouseleave);
                this.map.removeLayer('enterprise-point-highlight-layer');
            }

            if (this.map.getLayer('enterprise-point-highlight-text-layer')) {
                this.map.removeLayer('enterprise-point-highlight-text-layer');
            }

            if (this.map.getSource('enterprise-geojson-source')) {
                this.map.removeSource('enterprise-geojson-source');
            }
        },
        //大地测量落点maplibre-gl的mbtiles选中状态
        geodetic_pointchecked_state() {
            const isVisibleLocal = !this.isGeodetic
            const filterValue = isVisibleLocal ? 'visible' : this.currentKey
            const filterVariants = [filterValue, String(filterValue), Number(filterValue)]

            const createFilter = (operator) => ['any', ...filterVariants.map((v) => [operator, 'STN_NO', v])]

            const layers = [
                { id: 'geodetic-BM_point-layer', compare: isVisibleLocal ? '==' : '!=' },
                { id: 'geodetic-BM_point-text-layer', compare: isVisibleLocal ? '==' : '!=' },
                { id: 'geodetic-BM_point-highlight-layer', compare: isVisibleLocal ? '==' : '==' },
                { id: 'geodetic-Traverse_point-layer', compare: isVisibleLocal ? '==' : '!=' },
                { id: 'geodetic-Traverse_point-text-layer', compare: isVisibleLocal ? '==' : '!=' },
                { id: 'geodetic-Traverse_point-highlight-layer', compare: isVisibleLocal ? '==' : '==' },
                { id: 'geodetic-Trig_point-layer', compare: isVisibleLocal ? '==' : '!=' },
                { id: 'geodetic-Trig_point-text-layer', compare: isVisibleLocal ? '==' : '!=' },
                { id: 'geodetic-Trig_point-highlight-layer', compare: isVisibleLocal ? '==' : '==' }
            ]

            layers.forEach(({ id, compare }) => {
                if (this.map.getLayer(id)) {
                    this.map.setFilter(id, createFilter(compare))
                }
            })
        },
        //大地测量落点maplibre-gl的mbtiles
        fetchGeodeticPointsInView() {
            const layerExists = this.map.getLayer('geodetic-BM_point-layer') !== undefined;
            const sourceExists = this.map.getSource('geodetic-vector-source') !== undefined;

            if (!layerExists && !sourceExists) {
                this.map.addSource('geodetic-vector-source', {
                    type: 'vector',
                    url: gl.VECTORLAYER + '/data/geodetic.json'
                });

                const pointsText = {
                    type: 'symbol',
                    source: 'geodetic-vector-source',
                    minzoom: 14,
                    layout: {
                        'text-field': '{STN_NO}',
                        'text-allow-overlap': true,
                        'text-size': 10,
                        'text-font': ['SYCN Normal'],
                        'text-offset': [2, -1]
                    },
                    paint: {
                        'text-color': '#ff0000',
                        'text-halo-color': '#ffffff',
                        'text-halo-width': 2
                    }
                };

                // --- BM ---
                const BM_point = {
                    type: 'symbol',
                    source: 'geodetic-vector-source',
                    'source-layer': 'BM_point',
                    layout: {
                        'icon-image': 'icon-2-1',
                        'text-allow-overlap': true,
                        'icon-allow-overlap': true,
                        'icon-size': 0.06,
                        'icon-anchor': 'center',
                        'icon-offset': [0, 0]
                    },
                    filter: ['!=', 'STN_NO', this.currentKey]
                };
                this.map.addLayer({ ...BM_point, id: 'geodetic-BM_point-layer' });
                this.map.addLayer({ ...pointsText, id: 'geodetic-BM_point-text-layer', 'source-layer': 'BM_point' });

                BM_point.layout['icon-image'] = 'icon-2-0';
                BM_point.filter = ['==', 'STN_NO', this.currentKey];
                this.map.addLayer({ ...BM_point, id: 'geodetic-BM_point-highlight-layer' });

                // --- Traverse ---
                const Traverse_point = {
                    type: 'symbol',
                    source: 'geodetic-vector-source',
                    'source-layer': 'Traverse_point',
                    layout: {
                        'icon-image': 'icon-1-1',
                        'text-allow-overlap': true,
                        'icon-allow-overlap': true,
                        'icon-size': 0.05,
                        'icon-anchor': 'center',
                        'icon-offset': [0, 0]
                    },
                    filter: ['!=', 'STN_NO', this.currentKey]
                };
                this.map.addLayer({ ...Traverse_point, id: 'geodetic-Traverse_point-layer' });
                this.map.addLayer({ ...pointsText, id: 'geodetic-Traverse_point-text-layer', 'source-layer': 'Traverse_point' });

                Traverse_point.layout['icon-image'] = 'icon-1-0';
                Traverse_point.filter = ['==', 'STN_NO', this.currentKey];
                this.map.addLayer({ ...Traverse_point, id: 'geodetic-Traverse_point-highlight-layer' });

                // --- Trig ---
                const Trig_point = {
                    type: 'symbol',
                    source: 'geodetic-vector-source',
                    'source-layer': 'Trig_point',
                    layout: {
                        'icon-image': 'icon-0-1',
                        'text-allow-overlap': true,
                        'icon-allow-overlap': true,
                        'icon-size': 0.05,
                        'icon-anchor': 'center',
                        'icon-offset': [0, 0]
                    },
                    filter: ['!=', 'STN_NO', this.currentKey]
                };
                this.map.addLayer({ ...Trig_point, id: 'geodetic-Trig_point-layer' });
                this.map.addLayer({ ...pointsText, id: 'geodetic-Trig_point-text-layer', 'source-layer': 'Trig_point' });

                Trig_point.layout['icon-image'] = 'icon-0-0';
                Trig_point.filter = ['==', 'STN_NO', this.currentKey];
                this.map.addLayer({ ...Trig_point, id: 'geodetic-Trig_point-highlight-layer' });

                // --- Events ---
                const map = this.map;
                map.on('click', 'geodetic-BM_point-layer', this.unifiedLayerClickEvent);
                map.on('click', 'geodetic-Traverse_point-layer', this.unifiedLayerClickEvent);
                map.on('click', 'geodetic-Trig_point-layer', this.unifiedLayerClickEvent);

                ['BM', 'Traverse', 'Trig'].forEach(type => {
                    map.on('mouseenter', `geodetic-${type}_point-layer`, this.handleLotglaPolygonMouseenter);
                    map.on('mouseleave', `geodetic-${type}_point-layer`, this.handleLotglaPolygonMouseleave);
                    map.on('mouseenter', `geodetic-${type}_point-highlight-layer`, this.handleLotglaPolygonMouseenter);
                    map.on('mouseleave', `geodetic-${type}_point-highlight-layer`, this.handleLotglaPolygonMouseleave);
                });
            }
        },
        //大地测量落点移除maplibre-gl的mbtiles
        removeGeodeticVectorTileLayer() {
            const map = this.map;
            const layers = [
                'geodetic-BM_point-layer',
                'geodetic-BM_point-highlight-layer',
                'geodetic-Traverse_point-layer',
                'geodetic-Traverse_point-highlight-layer',
                'geodetic-Trig_point-layer',
                'geodetic-Trig_point-highlight-layer',
                'geodetic-BM_point-text-layer',
                'geodetic-Traverse_point-text-layer',
                'geodetic-Trig_point-text-layer'
            ];

            layers.forEach(id => {
                if (map.getLayer(id)) {
                    map.removeLayer(id);
                }
            });

            // 移除事件监听
            ['BM', 'Traverse', 'Trig'].forEach(type => {
                if (map.getLayer(`geodetic-${type}_point-layer`)) {
                    map.off('click', `geodetic-${type}_point-layer`, this.unifiedLayerClickEvent);
                    map.off('mouseenter', `geodetic-${type}_point-layer`, this.handleLotglaPolygonMouseenter);
                    map.off('mouseleave', `geodetic-${type}_point-layer`, this.handleLotglaPolygonMouseleave);
                }
                if (map.getLayer(`geodetic-${type}_point-highlight-layer`)) {
                    map.off('mouseenter', `geodetic-${type}_point-highlight-layer`, this.handleLotglaPolygonMouseenter);
                    map.off('mouseleave', `geodetic-${type}_point-highlight-layer`, this.handleLotglaPolygonMouseleave);
                }
            });

            if (map.getSource('geodetic-vector-source')) {
                map.removeSource('geodetic-vector-source');
            }
        },
        //大地测量落点maplibre-gl的mbtiles点击事件
        geodetic_point_click(e) {
            const feature = e.features?.[0];
            if (!feature || this.currentKey === feature.properties.STN_NO) return;

            this.currentKey = feature.properties.STN_NO;

            if (this.currentMode != 'hk1980' && this.currentMode != 'geodetic') this.removeTooltip()

            this.currentRenderCallback(this.currentKey, 'geodetic');
        },
        //地段/拨地maplibre-gl的mbtiles
        loadVectorTileLayer() {
            if (!this.map) return;

            const layerExists = this.map.getLayer('lotgla-polygon-layer') !== undefined;
            const sourceExists = this.map.getSource('lotgla-vector-source') !== undefined;

            if (!layerExists && !sourceExists) {
                this.map.addSource('lotgla-vector-source', {
                    type: 'vector',
                    url: gl.VECTORLAYER + '/data/tiles.json'
                });

                // 区块范围-透明（主-点击事件）
                this.map.addLayer({
                    id: 'lotgla-polygon-layer',
                    type: 'fill',
                    source: 'lotgla-vector-source',
                    'source-layer': 'lot_layer',
                    paint: {
                        'fill-color': '#000000',
                        'fill-opacity': 0
                    }
                });

                // 区块范围-红色虚线
                this.map.addLayer({
                    id: 'lotgla-polygon-outline',
                    type: 'line',
                    source: 'lotgla-vector-source',
                    'source-layer': 'lot_layer',
                    paint: {
                        'line-color': '#ff0000',
                        'line-width': 1.5,
                        'line-dasharray': [4, 2]
                    }
                });

                // 选中区块组范围-蓝色虚线
                this.map.addLayer({
                    id: 'lotgla-polygon-highlight-outline',
                    type: 'line',
                    source: 'lotgla-vector-source',
                    'source-layer': 'lot_layer',
                    paint: {
                        'line-color': '#0000FF',
                        'line-width': 3,
                        'line-dasharray': [4, 2]
                    }
                });

                // 选中高亮区块
                this.map.addLayer({
                    id: 'lotgla-polygon-highlight',
                    type: 'fill',
                    source: 'lotgla-vector-source',
                    'source-layer': 'lot_layer',
                    paint: {
                        'fill-color': '#8EA5FF',
                        'fill-opacity': 0.7
                    },
                    filter: ['==', 'LOTID', '']
                });

                // 事件监听，记得把这几个方法写在 methods 里或绑定this
                this.map.on('click', 'lotgla-polygon-layer', this.unifiedLayerClickEvent);
                this.map.on('mouseenter', 'lotgla-polygon-layer', this.handleLotglaPolygonMouseenter);
                this.map.on('mouseleave', 'lotgla-polygon-layer', this.handleLotglaPolygonMouseleave);
            }

            this.unifiedLayerStateManagement()
        },
        //移除maplibre-gl的mbtiles
        removeVectorTileLayer() {
            if (!this.map) return;

            if (this.map.getLayer('lotgla-polygon-layer')) {
                this.map.off('click', 'lotgla-polygon-layer', this.unifiedLayerClickEvent);
                this.map.off('mouseenter', 'lotgla-polygon-layer', this.handleLotglaPolygonMouseenter);
                this.map.off('mouseleave', 'lotgla-polygon-layer', this.handleLotglaPolygonMouseleave);
                this.map.removeLayer('lotgla-polygon-layer');
            }

            if (this.map.getLayer('lotgla-polygon-outline')) {
                this.map.removeLayer('lotgla-polygon-outline');
            }

            if (this.map.getLayer('lotgla-polygon-highlight-outline')) {
                this.map.removeLayer('lotgla-polygon-highlight-outline');
            }

            if (this.map.getLayer('lotgla-polygon-highlight')) {
                this.map.removeLayer('lotgla-polygon-highlight');
            }

            if (this.map.getLayer('lotgla-polygon-text-layer')) {
                this.map.removeLayer('lotgla-polygon-text-layer');
            }

            if (this.map.getSource('lotgla-vector-source')) {
                this.map.removeSource('lotgla-vector-source');
            }
        },
        //maplibre-gl的mbtiles点击事件
        handleLotglaPolygonClick(e) {
            const feature = e.features && e.features[0];
            if (!feature || this.currentKey === feature.properties.LOTID) return;
            this.currentKey = feature.properties.LOTID;
            this.currentRenderCallback(this.currentKey, 'lotgla');
        },
        //maplibre-gl的mbtiles鼠标Mouseenter事件
        handleLotglaPolygonMouseenter(e) {
            if (this.map) {
                this.map.getCanvas().style.cursor = 'pointer';
            }
        },
        //maplibre-gl的mbtiles鼠标Mouseleave事件
        handleLotglaPolygonMouseleave(e) {
            if (this.map) {
                this.map.getCanvas().style.cursor = 'default';
            }
        },
        locationAllocationFontLayer: debounce(function () {

            if (!this?.map) return;
            const mapInstance = this.map;

            const zoom = mapInstance.getZoom();
            const minzoom = 16.74;
            const polygonLayerId = 'lotgla-polygon-layer';
            const textSourceId = 'lotgla-polygon-text-source';
            const textLayerId = 'lotgla-polygon-text-layer';
            const textHighlightLayerId = 'lotgla-polygon-highlight-text-layer';

            const layerExists = mapInstance.getLayer(polygonLayerId) !== undefined;

            // 如果图层不存在或缩放级别过低，不需要处理
            if (!layerExists || zoom < minzoom) {
                this.removeLocationAllocationFontLayer();
                return;
            }

            const rendered = mapInstance.queryRenderedFeatures({ layers: [polygonLayerId] });

            // 使用 Map 提高按 LOTID 分组的效率
            const featuresByLotId = new Map();

            rendered.forEach(feature => {
                const lotId = feature.properties.LOTID;
                if (!featuresByLotId.has(lotId)) {
                    featuresByLotId.set(lotId, {
                        type: 'Feature',
                        properties: feature.properties,
                        geometry: {
                            type: 'MultiPolygon',
                            coordinates: []
                        }
                    });
                }
                const groupedFeature = featuresByLotId.get(lotId);

                // 合并坐标
                if (feature.geometry.type === 'Polygon') {
                    groupedFeature.geometry.coordinates.push(feature.geometry.coordinates);
                } else if (feature.geometry.type === 'MultiPolygon') {
                    groupedFeature.geometry.coordinates.push(...feature.geometry.coordinates);
                }
            });

            // 将 Map 转为数组，并计算中心点
            const mergedFeatures = [...featuresByLotId.values()].map(feature => {
                const center = centerOfMass(feature);
                center.properties = { ...feature.properties };
                return center;
            });

            const updatedGeoJSON = {
                type: 'FeatureCollection',
                features: mergedFeatures
            };

            const textSourceExists = mapInstance.getSource(textSourceId) !== undefined;

            if (!textSourceExists) {
                // 添加文字图层
                mapInstance.addSource(textSourceId, {
                    type: 'geojson',
                    data: updatedGeoJSON
                });

                mapInstance.addLayer({
                    id: textLayerId,
                    type: 'symbol',
                    source: textSourceId,
                    minzoom: minzoom,
                    layout: {
                        'text-field': '{LOTDISPLAYNAME}',
                        'text-allow-overlap': true,
                        'text-size': ['interpolate', ['linear'], ['zoom'], 14, 3, 17, 6, 20, 14],
                        'symbol-placement': 'point',
                        'text-anchor': 'center',
                        'text-font': ['SYCN Bold']
                    },
                    paint: {
                        'text-color': '#000',
                        'text-halo-color': '#ffffff',
                        'text-halo-width': 2
                    },
                    filter: ['!=', 'LOTID', this.currentKey]
                });

                mapInstance.addLayer({
                    id: textHighlightLayerId,
                    type: 'symbol',
                    source: textSourceId,
                    minzoom: minzoom,
                    layout: {
                        'text-field': '{LOTDISPLAYNAME}',
                        'text-allow-overlap': true,
                        'text-size': ['interpolate', ['linear'], ['zoom'], 14, 5, 17, 10, 20, 16],
                        'symbol-placement': 'point',
                        'text-anchor': 'center',
                        'text-font': ['SYCN Bold']
                    },
                    paint: {
                        'text-color': '#0000FF',
                        'text-halo-color': '#ffffff',
                        'text-halo-width': 10
                    },
                    filter: ['==', 'LOTID', this.currentKey]
                });

            } else {
                // 更新数据
                const source = mapInstance.getSource(textSourceId);
                if (source && 'setData' in source) {
                    source.setData(updatedGeoJSON);
                }
            }
        }, 300),
        removeLocationAllocationFontLayer() {
            const layerId = 'lotgla-polygon-text-layer'
            const sourceId = 'lotgla-polygon-text-source'
            const textHighlightLayerId = 'lotgla-polygon-highlight-text-layer'

            if (this.map.getLayer(layerId)) this.map.removeLayer(layerId)
            if (this.map.getLayer(textHighlightLayerId)) this.map.removeLayer(textHighlightLayerId)
            if (this.map.getSource(sourceId)) this.map.removeSource(sourceId)
        },
        locationAllocationFontLayer_state() {
            const isVisibleLocal = !this.isLotgla
            const filterValue = isVisibleLocal ? 'visible' : this.currentKey

            const textLayerId = 'lotgla-polygon-text-layer'
            const textHighlightLayerId = 'lotgla-polygon-highlight-text-layer'

            if (this.map.getLayer(textLayerId)) this.map.setFilter(textLayerId, [isVisibleLocal ? '==' : '!=', 'LOTID', filterValue])
            if (this.map.getLayer(textHighlightLayerId)) this.map.setFilter(textHighlightLayerId, [isVisibleLocal ? '==' : '==', 'LOTID', filterValue])
        },
        unifiedLayerClickEvent(e) {
            const feature = this.layerPriorityEvent(e)
            if (!feature) return
            const layerId = feature.layer.id
            if (layerId === 'enterprise-point-layer') {
                this.enterprise_point_click(e)
            } else if (layerId === 'geodetic-BM_point-layer') {
                this.geodetic_point_click(e)
            } else if (layerId === 'geodetic-Traverse_point-layer') {
                this.geodetic_point_click(e)
            } else if (layerId === 'geodetic-Trig_point-layer') {
                this.geodetic_point_click(e)
            } else if (layerId === 'lotgla-polygon-layer') {
                this.handleLotglaPolygonClick(e)
            } else if (layerId === 'searchFor-customLayer-layer') {
                if (this.currentKey === feature.properties.id) return
                const object = feature.properties
                this.currentKey = object.id
                this.currentRenderCallback({ mode: 'searchFor', 'searchForKey': this.searchForKey, id: object.id, data: object }, 'searchFor');
                this.customLayerClick('searchFor', e)
            } else if (layerId === 'hk1980-customLayer-layer') {
                if (this.currentKey === feature.properties.id) return
                const object = feature.properties
                this.currentKey = object.id
                this.currentRenderCallback({ mode: 'hk1980', id: object.id }, 'hk1980');
                this.customLayerClick('hk1980', e)
            }
        },
        layerPriorityEvent(e) {
            const feature = e.features?.[0]
            if (!feature) return

            const visibleLayerIds = this.map
                .getStyle()
                .layers.map((layer) => layer.id)
                .filter((id) => this.layerOrder.includes(id))

            const rangeFeatures = this.map.queryRenderedFeatures(e.point, { layers: visibleLayerIds })
            const layerId = feature.layer.id
            const layerIds = rangeFeatures
                .map((f) => f.layer?.id)
                .filter(Boolean)
                .sort((x, y) => this.layerOrder.indexOf(x) - this.layerOrder.indexOf(y))

            if (rangeFeatures?.length === 1 || (layerIds?.length > 1 && layerId === layerIds[0])) {
                return feature
            }
            return false
        },

        addCustomLayerPoints(key, data) {
            const layerExists = !!this.map.getLayer(`${key}-customLayer-layer`)
            const sourceExists = !!this.map.getSource(`${key}-customLayer-source`)

            if (!layerExists && !sourceExists) {
                const geojson = {
                    type: 'FeatureCollection',
                    features: data.map((item) => ({
                        type: 'Feature',
                        properties: { ...item },
                        geometry: { type: 'Point', coordinates: [item.lon, item.lat] }
                    }))
                }

                this.map.addSource(`${key}-customLayer-source`, { type: 'geojson', data: geojson })

                this.map.addLayer({
                    id: `${key}-customLayer-layer`,
                    type: 'symbol',
                    source: `${key}-customLayer-source`,
                    layout: {
                        'icon-allow-overlap': true,
                        'icon-image': 'my-points-icon-2',
                        'icon-size': 0.2,
                        'icon-anchor': 'bottom'
                    }
                })

                this.map.addLayer({
                    id: `${key}-customLayer-highlight-layer`,
                    type: 'symbol',
                    source: `${key}-customLayer-source`,
                    layout: {
                        'icon-allow-overlap': true,
                        'icon-image': 'my-points-icon-2',
                        'icon-size': 0.2,
                        'icon-anchor': 'center'
                    },
                    paint: {
                        'icon-opacity': this.currentMode === 'searchFor' ? 0 : 1
                    },
                    filter: ['==', 'id', this.currentKey]
                })

                this.map.on('click', `${key}-customLayer-layer`, this.unifiedLayerClickEvent)
                this.map.on('mouseenter', `${key}-customLayer-layer`, this.handleLotglaPolygonMouseenter)
                this.map.on('mouseleave', `${key}-customLayer-layer`, this.handleLotglaPolygonMouseleave)
            }

            this.unifiedLayerStateManagement()
        },

        removeCustomLayerPoints(key) {
            if (this.map.getLayer(`${key}-customLayer-layer`)) {
                this.map.off('click', `${key}-customLayer-layer`, this.unifiedLayerClickEvent)
                this.map.off('mouseenter', `${key}-customLayer-layer`, this.handleLotglaPolygonMouseenter)
                this.map.off('mouseleave', `${key}-customLayer-layer`, this.handleLotglaPolygonMouseleave)
                this.map.removeLayer(`${key}-customLayer-layer`)
            }
            if (this.map.getLayer(`${key}-customLayer-highlight-layer`)) this.map.removeLayer(`${key}-customLayer-highlight-layer`)
            if (this.map.getSource(`${key}-customLayer-source`)) this.map.removeSource(`${key}-customLayer-source`)
        },

        customLayerClick(key, e) {
            const Tzoom = this.map.getZoom()
            this.map.easeTo({ center: e.lngLat, zoom: Tzoom, offset: [0, 0], duration: 1000 })
        },
        custom_pointchecked_state(key) {
            if (this.map.getLayer(`${key}-customLayer-highlight-layer`)) this.map.setFilter(`${key}-customLayer-highlight-layer`, ['==', 'id', this.currentKey])
            if (this.map.getLayer(`${key}-customLayer-layer`)) this.map.setFilter(`${key}-customLayer-layer`, ['!=', 'id', this.currentKey])
            if (key == 'searchFor' && this.currentMode != 'searchFor') {
                this.removeTooltip()
            }
        },
        unifiedLayerStateManagement() {
            this.lotgla_pointchecked_state()
            this.locationAllocationFontLayer_state()
            this.geodetic_pointchecked_state()
            this.enterprise_pointchecked_state()
            this.custom_pointchecked_state('hk1980')
            this.custom_pointchecked_state('searchFor')
        },
        isSearchMode() {
            return ['hk1980', 'searchFor'].includes(this.currentMode)
        },
        // 添加/更新搜索位置的落点图层
        addSearchLocationLandingPoint(data) {
            if (this.isSearchMode()) {
                if (this.isLotgla) this.loadVectorTileLayer()
                if (this.isGeodetic) {
                    this.checkTheLandingPointOfTheEnterprise()
                    this.fetchGeodeticPointsInView()
                }
            }
            this.addCustomLayerPoints(this.currentMode, data)
            this.map.moveLayer(`${this.currentMode}-customLayer-layer`);
        },
        lotgla_pointchecked_state() {
            const isVisibleLocal = !this.isLotgla
            const isShow = this.displayAll ? 'visible' : 'none'
            const filterValue = isVisibleLocal ? '__none__' : this.currentKey

            if (isVisibleLocal) {
                if (this.map.getLayer('lotgla-polygon-layer')) this.map.setFilter('lotgla-polygon-layer', ['==', 'LOTID', filterValue])
                if (this.map.getLayer('lotgla-polygon-highlight')) this.map.setFilter('lotgla-polygon-highlight', ['==', 'LOTID', filterValue])
                if (this.map.getLayer('lotgla-polygon-highlight-outline')) this.map.setFilter('lotgla-polygon-highlight-outline', ['==', 'LOTID', filterValue])
                if (this.map.getLayer('lotgla-polygon-outline')) this.map.setFilter('lotgla-polygon-outline', ['==', 'LOTID', filterValue])
            } else {
                if (this.map.getLayer('lotgla-polygon-layer')) this.map.setFilter('lotgla-polygon-layer', ['!=', 'LOTID', ''])
                if (this.map.getLayer('lotgla-polygon-outline')) this.map.setLayoutProperty('lotgla-polygon-outline', 'visibility', isShow)
                if (this.map.getLayer('lotgla-polygon-highlight')) this.map.setFilter('lotgla-polygon-highlight', ['==', 'LOTID', filterValue])

                if (this.containKeys.length > 0 && this.currentMode === 'lotgla') {
                    if (this.map.getLayer('lotgla-polygon-highlight-outline')) this.map.setFilter('lotgla-polygon-highlight-outline', ['in', 'LOTID', ...this.containKeys])
                    if (this.map.getLayer('lotgla-polygon-outline')) this.map.setFilter('lotgla-polygon-outline', ['!in', 'LOTID', ...this.containKeys])
                } else {
                    if (this.map.getLayer('lotgla-polygon-highlight-outline')) this.map.setFilter('lotgla-polygon-highlight-outline', ['==', 'LOTID', '__none__'])
                    if (this.map.getLayer('lotgla-polygon-outline')) this.map.setFilter('lotgla-polygon-outline', ['!=', 'LOTID', ''])
                }
            }
        },

        flyTocenterRjs(data) {
            if (this.map && data?.center?.length == 2) {
                this.currentMode = 'searchFor';
                if (this.currentMode === 'searchFor') {
                    let title = data.params?.ename || data.params?.eaddress || ""
                    this.isShowLGLayers = true;
                    this.isGeodetic = data.isGeodetic;
                    this.isLotgla = data.isLotgla;
                    this.jumpToCoordinates(data.params.id, data.center, 16);
                    this.createTooltip(data.center, title, data.params)
                }
            }
        },
        layerStateManagementGeodeticRjs(data) {
            if (data === '' || !this.isShowLGLayers) return;
            this.isGeodetic = data;
        },
        layerStateManagementLotglaRjs(data) {
            if (data === '' || !this.isShowLGLayers) return;
            this.isLotgla = data;
        },
        //跳转至坐标
        jumpToCoordinates(key, coordinates, targetZoom) {
            this.currentKey = key
            let offset = [0, 0]
            if (this.isSearchMode()) {
                this.addSearchLocationLandingPoint(this.source_data)
            } else if (this.currentMode === 'geodetic') {
                this.checkTheLandingPointOfTheEnterprise()
                this.fetchGeodeticPointsInView()
                offset = [0, 180];
            }
            this.unifiedLayerStateManagement()

            const currentZoomLocal = this.map.getZoom()
            this.map.easeTo({ center: coordinates, zoom: Math.max(currentZoomLocal, targetZoom), offset: offset, duration: 1000 })
        },
        //hk1980落点
        hk1980LandingPoint(data) {
            if (data == null || !data.center || (data.center).length === 0) return;
            this.currentMode = 'hk1980';
            this.isShowLGLayers = true;
            this.isGeodetic = data.isGeodetic;
            this.isLotgla = data.isLotgla;
            this.source_data = [{
                id: `${data.center[0]}_${data.center[1]}`,
                title: data.title,
                lon: data.center[0],
                lat: data.center[1],
                selected: true
            }];

            this.jumpToCoordinates(data.center[0] + "_" + data.center[1], data.center, 15);
        },
        //搜索定位落点
        searchForLandingPoint(data) {
            if (this.map && data && Object.keys(data).length > 0) {
                this.currentMode = 'searchFor';
                this.searchForKey = data.key || '';
                if (data.params?.length > 0)
                    this.addSearchLocationLandingPoint(data.params)
            }
        },
        //大地测量落点
        geodeticLandingPoint(data) {
            if (this.map && data?.coordinates?.length == 2) {
                this.currentMode = 'geodetic';
                if (!this.isShowLGLayers) {
                    this.isGeodetic = true;
                    this.isLotgla = false;
                } else {
                    this.isGeodetic = data.isGeodetic;
                    this.isLotgla = data.isLotgla;
                }
                this.jumpToCoordinates(data.key, data.coordinates, 15);
            }
        },
        //lotgla落点
        lotglaLandingPoint(info) {
            if (this.map && info?.data && info?.keyIds.length > 0) {
                const data = info?.data;
                const duration = 1000;
                this.currentKey = data?.pId;
                this.currentMode = 'lotgla';
                this.displayAll = true;
                this.containKeys = info.keyIds;
                if (!this.isShowLGLayers) {
                    this.isGeodetic = false;
                    this.isLotgla = true;
                } else {
                    this.isGeodetic = info.isGeodetic;
                    this.isLotgla = info.isLotgla;
                }
                this.loadVectorTileLayer();
                this.fitMapToCoordinates(data.coordinates, duration);
            } else {
                // this.resetMap();
            }
        },
        getBoundingCoordinates(coordinates) {
            if (!coordinates.length) {
                return {
                    min: [0, 0],
                    max: [0, 0]
                };
            }

            let minLng = Infinity;
            let minLat = Infinity;
            let maxLng = -Infinity;
            let maxLat = -Infinity;

            // 这里 coordinates[0] 是一组坐标数组，结构是 [[lng, lat], ...]
            coordinates[0].forEach(([lng, lat]) => {
                if (lng < minLng) minLng = lng;
                if (lat < minLat) minLat = lat;
                if (lng > maxLng) maxLng = lng;
                if (lat > maxLat) maxLat = lat;
            });

            return {
                min: [minLng, minLat],
                max: [maxLng, maxLat]
            };
        },
        fitMapToCoordinates(coordinates, duration) {
            if (!this.map || !coordinates || coordinates.length === 0) return;

            const lngLatBounds = this.getBoundingCoordinates(coordinates);

            const bounds = new maplibregl.LngLatBounds(
                [lngLatBounds.min[0], lngLatBounds.min[1]],
                [lngLatBounds.max[0], lngLatBounds.max[1]]
            );

            this.map.fitBounds(bounds, {
                padding: 100,
                duration: duration,
                offset: [0, 90],
                maxZoom: 18
            });
        },
        loadDynamicIconsCategory(rows) {
            if (Object.keys(rows).length > 0) {
                for (let key in rows) {
                    this.loadNetworkImage(rows[key], (err, image) => {
                        if (err) {
                            console.error('加载失败', err);
                            return;
                        }
                        if (!this.map.hasImage(key)) {
                            this.map.addImage(key, image);
                        }
                    });
                }
            }
        },
        loadNetworkImage(url, callback) {
            const img = new Image();
            img.crossOrigin = "anonymous";
            img.onload = () => {
                const canvas = document.createElement("canvas");
                canvas.width = img.width;
                canvas.height = img.height;
                const ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0);
                callback(null, ctx.getImageData(0, 0, img.width, img.height));
            };
            img.onerror = e => callback(e, null);
            img.src = url;
        },
        isInHKBounds(lon, lat) {
            const [[minLon, minLat], [maxLon, maxLat]] = this.hkBounds;
            return lon >= minLon && lon <= maxLon && lat >= minLat && lat <= maxLat;
        },
        getCurrentPosition(data) {
            if (this.map && data && Object.keys(data).length > 0) {

                if (this.map.getLayer('my-points-layer')) {
                    this.map.removeLayer('my-points-layer');
                }
                if (this.map.getSource('my-points-source')) {
                    this.map.removeSource('my-points-source');
                }

                if (data.isOpen == false) {
                    return;
                }

                const lon = data.longitude;
                const lat = data.latitude;

                if (this.isInHKBounds(lon, lat)) {
                    this.map.addSource('my-points-source', {
                        type: 'geojson',
                        data: {
                            type: 'FeatureCollection',
                            features: [
                                {
                                    type: 'Feature',
                                    properties: { icon: 'my-points-icon' },
                                    geometry: {
                                        type: 'Point',
                                        coordinates: [lon, lat],
                                    },
                                },
                            ],
                        },
                    });

                    this.map.addLayer({
                        id: 'my-points-layer',
                        type: 'symbol',
                        source: 'my-points-source',
                        layout: {
                            'icon-image': 'my-points-icon',
                            'icon-size': 0.2,
                            'icon-anchor': 'bottom',
                        },
                    });

                    // 只有首次定位或用户主动定位时才移动地图
                    if (data.isMove) {
                        const currentZoom = this.map.getZoom();
                        this.map.easeTo({
                            center: [lon, lat],
                            zoom: currentZoom > 15 ? currentZoom : 15,
                            offset: [0, 0],
                            duration: 1000,
                        });
                        this.$ownerInstance.callMethod('successLocation');
                    }
                    
                    // 定位成功后，始终检查并加载图层（不依赖 isMove）
                    // 从 data 中获取配置状态（由 index.vue 传递）

                    const isGeodeticEnabled = data.isGeodetic || false;
                    const isLotglaEnabled = data.isLotgla || false;
                    
                    if (isGeodeticEnabled || isLotglaEnabled) {
                        // 首次加载时设置模式和标志
                        if (!this.isShowLGLayers) {
                            console.log('✅ 首次加载，设置模式和标志');
                            this.currentMode = 'searchFor';
                            this.isShowLGLayers = true;
                        }
                        
                        // 如果大地测量站开关开启且未加载
                        if (isGeodeticEnabled) {
                            console.log('🗺️ 准备加载大地测量站...');
                            if (!this.isGeodetic) {
                                this.isGeodetic = true;
                                console.log('   设置 isGeodetic = true');
                            }
                            // 直接调用加载方法，不依赖 watch
                            console.log('   调用 fetchGeodeticPointsInView()');
                            this.fetchGeodeticPointsInView();
                            this.checkTheLandingPointOfTheEnterprise();
                        } else if (this.isGeodetic) {
                            console.log('❌ 大地测量站开关关闭，隐藏图层');
                            this.isGeodetic = false;
                        }
                        
                        // 如果地段开关开启且未加载
                        if (isLotglaEnabled) {
                            console.log('🗺️ 准备加载地段...');
                            if (!this.isLotgla) {
                                this.isLotgla = true;
                                console.log('   设置 isLotgla = true');
                            }
                            // 直接调用加载方法，不依赖 watch
                            console.log('   调用 loadVectorTileLayer()');
                            this.loadVectorTileLayer();
                        } else if (this.isLotgla) {
                            console.log('❌ 地段开关关闭，隐藏图层');
                            this.isLotgla = false;
                        }
                    } else {
                        console.log('⚠️ 所有开关都关闭');
                    }
                } else {
                    this.$ownerInstance.callMethod('offscaleLocation');
                }
            }
        },
        currentRenderCallback(data, mode) {
            this.$ownerInstance.callMethod('callCurrentCallback', { data, mode });
        },
        createTooltip(center, title, params) {
            this.removeTooltip();
            let then = this;
            const tooltip = this.currentLocation.node != '' ? this.currentLocation.node : document.getElementById('tooltip');
            if (tooltip) {
                this.currentLocation = {
                    status: true,
                    center: center,
                    title: title,
                    params: params,
                    node: tooltip,
                }
                tooltip.querySelector('.title').innerHTML = this.currentLocation.title;
                if (Object.keys(params).length > 0) {
                    tooltip.querySelector('.isLink').style.display = 'block';
                    tooltip.querySelector('.content').onclick = function () {
                        then.$ownerInstance.callMethod('onTClick', params);
                    };
                }
                const pixel = this.map.project(this.currentLocation.center);
                tooltip.style.left = pixel.x + 'px';
                tooltip.style.top = (pixel.y - 1) + 'px';
                tooltip.style.display = 'block';
            }
        },
        moveTooltip() {
            const tooltip = this.currentLocation.node != '' ? this.currentLocation.node : document.getElementById('tooltip');
            if (tooltip && this.currentLocation.status == true && this.currentLocation.center) {
                const pixel = this.map.project(this.currentLocation.center);
                tooltip.style.left = pixel.x + 'px';
                tooltip.style.top = (pixel.y - 1) + 'px';
                tooltip.style.display = 'block';
            }
        },
        removeTooltip() {
            const tooltip = this.currentLocation.node != '' ? this.currentLocation.node : document.getElementById('tooltip');
            if (tooltip) {
                this.currentLocation = {
                    status: false,
                    center: [],
                    title: '',
                    params: {},
                    node: tooltip,
                }
                tooltip.querySelector('.content').onclick = null
                tooltip.querySelector('.isLink').style.display = 'none';
                tooltip.querySelector('.title').innerHTML = '';
                tooltip.style.left = '-1000px';
                tooltip.style.top = '-1000px';
                tooltip.style.display = 'none';
            }
        },
        // 重置地图
        resetMap() {
            if (!this.map) return;

            this.source_data = {};
            this.currentMode = '';
            this.currentKey = '';
            this.searchForKey = '';
            this.containKeys = [];
            this.displayAll = true;
            this.isGeodetic = false;
            this.isLotgla = false;
            this.isShowLGLayers = false;
            this.removeTooltip()

            this.removeVectorTileLayer();
            this.removeGeodeticVectorTileLayer()
            this.removeEnterpriseVectorTileLayer()

            this.removeLocationAllocationFontLayer()
            this.removeCustomLayerPoints('hk1980')
            this.removeCustomLayerPoints('searchFor')

            this.map.setMinZoom(this.minZoom);
            this.map.easeTo({
                center: this.center,
                zoom: this.zoom,
                offset: [0, 0],
                duration: 1000,
            });

            this.$nextTick(() => {
                if (typeof this.map.redraw === 'function') {
                    this.map.redraw();
                }
            });
        }
    }
}
